package algotithm.leetcode.dichotomy.interview1003;

/**
 * @author zhouyanxiang
 * @Date 2021-03-2021/3/30-23:49
 * @URL 面试题 10.03. 搜索旋转数组
 */
class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1,1,1,1,1,2,1,1,1};
        int target = 2;
        int search = solution.search(nums, target);
        System.out.println(search);
    }
    
    public int search(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            if (nums[l] == target) {
                return l;
            }
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) {
                r = mid;
            } else if (nums[mid] > nums[l]){
                if (nums[mid] >= target && target >= nums[l]) {
                    r = mid ;
                } else {
                    l = mid + 1;
                }
            } else if (nums[mid] < nums[l]) {
                if (nums[mid] <= target && target <= nums[r]) {
                    l = mid ;
                } else {
                    r = mid - 1;
                }
            }  else {
                l++;
            }
        }
        return -1;
    }

}
